<?php

namespace App\WechatHandlers;

use App\Models\KeywordRule;
use App\Models\Material;
use App\Services\WechatCustomService;
use EasyWeChat\Kernel\Contracts\EventHandlerInterface;

class TextMessageHandler extends MessageHandler implements EventHandlerInterface
{

    public function handle($payload = null)
    {
        // 获取关键字配置
        $keywordRule = KeywordRule::query()->with(['replies.material'])
            ->where('keyword', $payload['Content'])
            ->where('status', 1)
            ->first();

        if (!$keywordRule) {
            // 走普通回复，没有则直接返回
            $this->normalMsgReply(Material::TYPE_TEXT, $payload['FromUserName']);
        }

        // 判断回复类型
        if ($keywordRule['reply_mode'] === KeywordRule::REPLY_ALL) {
            foreach ($keywordRule->replies as $reply) {
                WechatCustomService::send($reply, $payload['FromUserName']);
            }
        } else {
            // 随机取一条回复
            if (count($keywordRule->replies) > 1) {
                $replyKey = array_rand($keywordRule->replies);
                $reply = $keywordRule->replies[$replyKey];
            } else {
                $reply = $keywordRule->replies[0];
            }
            WechatCustomService::send($reply, $payload['FromUserName']);
        }
    }
}